Categories
Flask

Python Web Development with Flask — Commands and Blueprints, Factories, and Exceptions

Spread the love

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Registering Commands with Blueprints

We can register commands with Blueprints.

For example, we can write:

from flask import Flask
import click
from flask import Blueprint
app = Flask(__name__)
bp = Blueprint('students', __name__)

@bp.cli.command('create')
@click.argument('name')
def create(name):
    print('create %s' % name)

app.register_blueprint(bp)

@app.route('/')
def hello_world():
    return 'hello world'

We create our blueprint with the Blueprint class.

Then we call @bp.cli.command decorator to create the 'create' command in the blueprint.

We specify the command line argument with the @click.argument decorator.

Then we call app.register_blueprint to register the blueprint.

Then when we run:

flask students create alice

We see ‘created alice’ displayed.

Application Context

We can use the @with_appcontext decorator to run the command function with the app context pushed.

This way, we have access to the app and its config in the command function.

For example, we can write:

from flask import Flask
import click
from flask.cli import with_appcontext
app = Flask(__name__)

@click.command('do_work')
@with_appcontext
def do_work():
    print(app)

app.cli.add_command(do_work)

@app.route('/')
def hello_world():
    return 'hello world'

to add the do_work task into our app.

When we run:

flask do_work

we see the app:

<Flask 'app'>

logged.

Application Factories

We can create a factory function for our app so that we can create multiple instances of our app.

This makes testing easier.

For example, we can write:

from flask import Flask

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    print(app.config)

    @app.route('/')
        def hello_world():
            return 'hello world'
    return app

create_app('config')

to create a create_app function that takes the config_filename parameter.

Then we can read the config parameter we want according to the value of config_filename .

API Exceptions

We can create our own exception classes and use them in our Flask app.

For example, we can write:

from flask import Flask, jsonify

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

app = Flask(__name__)

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/')
def hello_world():
    raise InvalidUsage('This view is gone', status_code=410)

We create the InvalidUsage class which extends the Exception class.

The __init__ method initializes the mesaage and payload values.

to_dict is a method that puts the instance variables into a dictionary and returns it.

Then we register the error handler for this exception with the handle_invalid_usage method.

The @app.errorhandler decorator is used to handle the errors.

In the function, we call error.to_dict() to get the dictionary version of the error and returns it as the JSON response.

Then in the hello_world route function, we raise the InvalidUsage exception.

And when we go to http://127.0.0.1:5000/, we see:

{
  "message": "This view is gone"
}

in the response.

Conclusion

We can register commands with blueprints, create app factory functions, and add our own API exceptions with Flask.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *